package domfarr;

/*
 * $HeadURL$
 * $Revision$
 * $Date$
 * ====================================================================
 *
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * [Additional notices, if required by prior licensing conditions]
 *
 */

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.cookie.CookieSpec;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.dom4j.Node;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.sun.org.apache.xerces.internal.parsers.DOMParser;

/**
 * 
 * This is a Swing application that demonstrates how to use the Jakarta
 * HttpClient multipart POST method for uploading files
 * 
 * @author Sean C. Sullivan
 * @author Michael Becke
 * 
 */
public class AutoFileUpload {

	private static final int PORT = 8080;
	private static final String HOST = "localhost";
	private static File targetFile = new File("C:\\cygwin\\home\\dom\\runway.docx");
	private static HttpClient client = new HttpClient();
	private static CookieSpec cookiespec = CookiePolicy.getDefaultSpec();

	public static void main(String[] args) {
		client.getHostConfiguration().setHost(HOST, PORT, "http");
		client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

		login();
		uploadArticle();

	}

	private static void uploadArticle() {
		PostMethod filePost = new PostMethod("/ic2/articles/create.createform");
		//filePost.addRequestHeader("Accept-Encoding", "gzip,deflate");
		try {
			Cookie[] initcookies = cookiespec.match(HOST, PORT, "/ic2", false, client.getState().getCookies());
			System.out.println("Initial set of cookies:");
			if (initcookies.length == 0) {
				System.out.println("None");
			} else {
				for (int i = 0; i < initcookies.length; i++) {
					System.out.println("- " + initcookies[i].toString());
				}
			}

			String formdata = getFormData();
			Part[] parts = { new FilePart(targetFile.getName(), targetFile), new StringPart("t:formdata", formdata),
					new StringPart("byline", "Dom"), new StringPart("displayDate", "15/01/2009"),
					new StringPart("formatTag", "NEWS"), new StringPart("icTags:values", "[\"BROADBAND\"]"),
					new StringPart("icTags", "BROADBAND"), new StringPart("topics:values", "[\"3\"]"), new StringPart("topics", "3"),
					new StringPart("companies:values", "[\"3\"]"), new StringPart("companies", "3"),
					new StringPart("countries", "WESTERN_EUROPE") };
			filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
			client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
			int status = client.executeMethod(filePost);
			if (status == HttpStatus.SC_OK) {
				System.out.println("Upload complete, response=" + filePost.getResponseBodyAsString());
			} else {
				System.out.println("Upload failed, response=" + HttpStatus.getStatusText(status));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			filePost.releaseConnection();
		}
	}

	private static String getFormData() {
		GetMethod get = new GetMethod("/ic2/articles/create");
		String response = null;
		try {
			client.executeMethod(get);
			response = get.getResponseBodyAsString();
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			get.releaseConnection();
		}
		int indexOfHidden = response.indexOf("hidden");
		int indexOfFormDataValueKey = response.indexOf("value", indexOfHidden);
		int indexOfFormDataValueStart = response.indexOf('"', indexOfFormDataValueKey);
		int indexOfFormDataValueEnd = response.indexOf('"', indexOfFormDataValueStart+1);
		String substring = response.substring(indexOfFormDataValueStart, indexOfFormDataValueEnd);
		
		return substring;
	}

	private static void login() {
		GetMethod authget = new GetMethod("/ic2/spring_security_login");
		PostMethod authpost = new PostMethod("/ic2/j_spring_security_check");
		try {
			client.executeMethod(authget);
			authget.releaseConnection();

			// Prepare login parameters
			NameValuePair action = new NameValuePair("action", "/ic2/j_spring_security_check");
			NameValuePair userid = new NameValuePair("j_username", "pub");
			NameValuePair password = new NameValuePair("j_password", "pub");
			authpost.setRequestBody(new NameValuePair[] { action, userid, password });

			client.executeMethod(authpost);
			System.out.println("Login form post: " + authpost.getStatusLine().toString());
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// release any connection resources used by the method
			authpost.releaseConnection();
		}
		// See if we got any cookies
		// The only way of telling whether logon succeeded is
		// by finding a session cookie
		Cookie[] logoncookies = cookiespec.match(HOST, PORT, "/ic2", false, client.getState().getCookies());
		System.out.println("Logon cookies:");
		if (logoncookies.length == 0) {
			System.out.println("None");
		} else {
			for (int i = 0; i < logoncookies.length; i++) {
				System.out.println("- " + logoncookies[i].toString());
			}
		}

		int statuscode = authpost.getStatusCode();
		if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
				|| (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
			Header header = authpost.getResponseHeader("location");
			if (header != null) {
				String newuri = header.getValue();
				System.out.println("Redirect target: " + newuri);
			} else {
				System.out.println("Invalid redirect");
				System.exit(1);
			}
		}

	}
}